import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Card, Form, Table, Divider, Row, Col, Select, Button, message, Spin } from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { Link } from 'dva/router';

import AutoCorrectTable from '../../components/_public/AutoCorrectTable';

import { getParamUrl } from '../../utils/formatDataSource';

@connect(({ lesson3, question3, loading }) => ({
  lesson:lesson3,
  question:question3,
  loading: loading.effects['question/complete'] || loading.effects['question/homeworkUserInfo'],
}))
class CheckHomework extends PureComponent {
  state = {
    currentCorrectStudentId: '',
  };

  componentDidMount() {
    const { dispatch, location: { search } } = this.props;

    const params = getParamUrl(search);

    dispatch({
      type: 'question3/homeworkUserInfo',
      payload: params,
    });

    dispatch({
      type: 'question3/checkList1',
      payload: {
        ...params,
        questionType: 1,
        isHomework: 1,
        examType: 4,
      },
    });
    dispatch({
      type: 'question3/checkList2',
      payload: {
        ...params,
        questionType: 2,
        isHomework: 1,
        examType: 4,
      },
    });
    dispatch({
      type: 'question3/checkList3',
      payload: {
        ...params,
        questionType: 3,
        isHomework: 1,
        examType: 4,
      },
    });
  }

  correct = (operateId, questionType, result, score) => {
    const { dispatch, location: { search } } = this.props;

    const params = getParamUrl(search);

    dispatch({
      type: 'question3/correct',
      payload: {
        operateId: operateId,
        result: result,
        score: score,
      },
    }).then(() => {
      dispatch({
        type: `question/checkList${questionType}`,
        payload: {
          ...params,
          questionType: questionType,
          isHomework: 1,
          examType: 4,
        },
      });
    });
  };

  complete = () => {
    const { dispatch, location: { search } } = this.props;

    const { xzData, tkData, jdData, homeworkUser } = this.props.question;

    const resultStudents = [];

    const studentArr = [];

    const totalDatas = [...xzData.data, ...tkData.data, ...jdData.data];

    if (totalDatas.length === 0) {
      message.error('当前课程无作业', 2);
      return;
    }
    if (!this.checkSubmit(totalDatas)) {
      message.error('已提交学生存在未批改题目', 2);
      return;
    }

    totalDatas[0].students.map(s => {
      studentArr.push({
        studentId: s.id,
        rightCount: 0,
        totalCount: totalDatas.length,
        score: 0,
      });
    });

    totalDatas.map(x => {
      const students = x.students;
      if (students) {
        console.log(students);
        students.map(s => {
          if (s.isRight === 1) {
            const oneStudent = studentArr.find(one => one.studentId === s.id);
            if (oneStudent) {
              const score = s.myScore ? s.myScore : 0;
              oneStudent.rightCount = oneStudent.rightCount + 1;
              oneStudent.score = oneStudent.score + score;
            }
          }
        });
      }
    });

    const params = getParamUrl(search);
    dispatch({
      type: 'question3/complete',
      payload: {
        ...params,
        studentStr: JSON.stringify(studentArr),
      },
    }).then(() => {
      homeworkUser.lessonStatus = 4;
      this.setState({
        homeworkUser,
      });
    });
  };

  checkSubmit = data => {
    const { homeworkUser: { submitStudents } } = this.props.question;
    let result = true;
    submitStudents.map(s => {
      data.map(data => {
        const students = data.students;
        if (students) {
          const one = students.find(stu => stu.id === s.id);
          if (one && one.isCorrect !== 1) {
            result = false;
          }
        }
      });
    });
    return result;
  };

  setCurrentStudentId = id => {
    this.setState({ currentCorrectStudentId: id });
  };

  render() {
    const { xzData, tkData, jdData, homeworkUser } = this.props.question;

    let submitCount = 0;
    let allCount = 0;
    if (Object.keys(homeworkUser).length !== 0) {
      const { submitStudents, allStudents } = homeworkUser;
      submitCount = submitStudents.length;
      allCount = allStudents.length;
    }

    return (
      <PageHeaderLayout>
        <Card>
          <Row>
            <Col span={4}>
              账号：<strong>{homeworkUser ? homeworkUser.name : ''}</strong>
            </Col>

            <Col span={4}>
              已交作业人数：<strong>
                {submitCount}/{allCount}
              </strong>
            </Col>
            <Col span={4}>
              <Spin spinning={this.props.loading}>
                <Button
                  type="primary"
                  onClick={this.complete}
                  hidden={homeworkUser.lessonStatus !== '3'}
                >
                  完成批改
                </Button>
              </Spin>
            </Col>
          </Row>
        </Card>
        <Card bordered={false} title="选择题（智能批改）">
          <AutoCorrectTable
            dataSource={xzData}
            handleCorrect={this.correct}
            questionType={1}
            lessonStatus={homeworkUser.lessonStatus}
            setCurrentId={this.setCurrentStudentId}
          />
        </Card>
        <Card bordered={false} title="填空题（老师批改）">
          <AutoCorrectTable
            dataSource={tkData}
            handleCorrect={this.correct}
            questionType={2}
            lessonStatus={homeworkUser.lessonStatus}
            setCurrentId={this.setCurrentStudentId}
          />
        </Card>
        <Card bordered={false} title="简答题（老师批改）">
          <AutoCorrectTable
            dataSource={jdData}
            handleCorrect={this.correct}
            questionType={3}
            lessonStatus={homeworkUser.lessonStatus}
            setCurrentId={this.setCurrentStudentId}
          />
        </Card>
      </PageHeaderLayout>
    );
  }
}


export default CheckHomework;
